package com.green_reading.mandolin;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.BindView;

import okhttp3.ResponseBody;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.Call;
import retrofit2.converter.gson.GsonConverterFactory;

import com.green_reading.mandolin.SimpleService.ServerAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class LoginActivity extends Activity {
    private final static String TAG = LoginActivity.class.getCanonicalName();
    private static final int REQUEST_SIGNUP = 0;

    @BindView(R.id.user_name) EditText user_name;
    @BindView(R.id.user_password) EditText user_password;
    @BindView(R.id.button_login) Button button_login;
    @BindView(R.id.button_signup) Button button_signup;

    protected void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        button_login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d(TAG, "Login");
                button_login.setEnabled(false);
                String user_name_str = user_name.getText().toString();
                String password_str = user_password.getText().toString();
                if(user_name_str.equals("") || password_str.equals("")) {
                    toast("user name or password invalid");
                    button_login.setEnabled(true);
                    return;
                }
                Log.d(TAG, "Login: " + user_name_str + " " + password_str);
                login(user_name_str, Util.md5(password_str));

            }
        });

        button_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
                startActivityForResult(intent, REQUEST_SIGNUP);
            }
        });
        //recoLiveInit("p2p0.reconova.com:3000", "");
    }

    private int login(String user_name, String password) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SimpleService.BASE_URL)
                .build();
        ServerAPI service = retrofit.create(ServerAPI.class);
        Call<ResponseBody> call = service.login(user_name, password);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                JSONObject responseJson = Util.parseResponse(response, TAG);
                if (response.code() == 200) {
                    Intent resultData = new Intent();
                    resultData.putExtra("user_name", responseJson.optString("name"));
                    resultData.putExtra("user_id", responseJson.optString("user_id"));
                    setResult(Activity.RESULT_OK, resultData);
                    finish();
                } else {
                    toast(responseJson.optString("detail"));
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        button_login.setEnabled(true);
                    }
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // Log error here since request failed
                toast("cannot connect to server");
                t.printStackTrace();
            }
        });
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SIGNUP) {
            if (resultCode == RESULT_OK) {
                button_login.setEnabled(true);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onDestroy() {
        super.onDestroy();
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Confirm");
            builder.setMessage("Are you sure to exit?");
            builder.setPositiveButton("YES", mDlgClick);
            builder.setNegativeButton("NO", mDlgClick);
            builder.show();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private DialogInterface.OnClickListener mDlgClick = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            if (which == AlertDialog.BUTTON_POSITIVE) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
    };
}